package com.xyzwps.harbor.service;

import com.xyzwps.harbor.model.User;
import com.xyzwps.harbor.model.UserStatus;
import com.xyzwps.harbor.repo.UserRepository;

import static com.xyzwps.harbor.util.HarborException.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;

@Service
public class UserService {

    @Autowired
    private UserIdGenerator userIdGenerator;

    @Autowired
    private PasswordService passwordService;

    @Autowired
    private UserRepository userRepository;


    // TODO: 事务
    public Mono<User> createUser(String username, String password) {
        return userIdGenerator.generate()
                .map(userId -> {
                    var user = new User();
                    user.setUserId(userId);
                    user.setUsername(username);
                    user.setAvatar("" );
                    user.setNickName(username);
                    user.setRegisterTime(LocalDateTime.now());
                    user.setStatus(UserStatus.ACTIVE);
                    return user;
                })
                .flatMap(user -> userRepository.insert(user).then(Mono.just(user)))
                .flatMap(user -> passwordService.createPassword(user.getUserId(), password).then(Mono.just(user)));
    }

    public Mono<User> login(String username, String realPassword) {
        return userRepository.selectByUsername(username)
                .switchIfEmpty(Mono.error(badRequestEx("user not exists." )))
                .map(User::shouldBeActive)
                .flatMap(user -> passwordService
                        .isMatchedPassword(user.getUserId(), realPassword)
                        .flatMap(it -> it ? Mono.just(user) : Mono.error(badRequestEx("password not matched" )))
                );
    }

    public Mono<User> getUserByUserId(long userId) {
        return userRepository.selectByUserId(userId);
    }
}